import re

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义登录响应数据
    """
    # print('======================')
    return {
        'username': user.username,
        "user_id": user.id,
        'token': token
    }


from django.contrib.auth.backends import ModelBackend


def get_user_by_account(account):
    '''
    account: 手机号或用户名
    '''
    try:
        # 根据手机号查询用户
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            # 根据用户名查询用户
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


# 自定义后端认证类
class UsernameMobleAuthBackend(ModelBackend):
    """
    Authenticates against settings.AUTH_USER_MODEL.
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        '''
        :param username:  用户名或手机号
        :param password: 密码
        '''
        # 1. 根据用户名后手机号查询用户
        user = get_user_by_account(username)
        # 2. 根据用户判断密码是否正确
        if user and user.check_password(password):
            return user
